<template>
  <div style="width: 100%; height: calc(100% - 50px)">
    <!-- v-on="gridEvents" overflow: hidden -->
    <vxe-grid ref="tableRef" v-bind="gridOptions" v-on="gridEvents">
      <template #toolbar_buttons>
        <div style="display: flex; margin-left: 10px">
          <div>
            <span style="font-size: 15px">数据来源</span>
            <Tooltip placement="top" :overlayStyle="{ width: '200px' }">
              <template #title>
                <div>
                  <div>收款确认: 金额(人民币) = (实收金额+折扣总金额+总手续费+总金额+总佣金)*汇率</div>
                  <div>销售预收款:金额(人民币) = 预收款总金额*汇率</div>
                </div>
              </template>
              <InfoCircleOutlined style="margin-left: 5px; color: #cc8500; font-size: 19px; cursor: pointer" />
            </Tooltip>
          </div>
          <div style="display: flex; align-items: center; margin-left: 15px">
            <span style="color: gray; font-size: 12px; cursor: pointer" @click="addExcludeFn">提交排除抽成</span>
            <span style="margin-left: 15px; color: gray; font-size: 12px; cursor: pointer"
              @click="getExcludeFn">查看已排除数据</span>
            <span class="table-header-btn" @click="openWaitFn" v-if="waitList.length"
              style="color: orange">查看数据处理队列</span>
          </div>
        </div>
      </template>
      <template #footer_totalAllPrice>
        <span style="color: red">{{ totalObj.totalAllPrice }}{{ totalObj.totalAllPrice ? '元' : '' }}
        </span>
      </template>
      <template #footer_orderCommissionPrice>
        <span style="color: red">{{ totalObj.orderCommissionPrice }}{{ totalObj.orderCommissionPrice ? '元' : ''
          }}</span>
      </template>
      <template #footer_receiverUserPrice>
        <span style="color: red">{{ totalObj.receiverUserPrice }}{{ totalObj.receiverUserPrice ? '元' : '' }}</span>
      </template>
      <template #footer_manageUserPrice>
        <span style="color: red">{{ totalObj.manageUserPrice }}{{ totalObj.manageUserPrice ? '元' : '' }}</span>
      </template>
      <template #footer_xiangMuGroupPrice>
        <span style="color: red">{{ totalObj.xiangMuGroupPrice }}{{ totalObj.xiangMuGroupPrice ? '元' : '' }}</span>
      </template>
      <template #footer_jiJingPrice>
        <span style="color: red">{{ totalObj.jiJingPrice }}{{ totalObj.jiJingPrice ? '元' : '' }}</span>
      </template>
      <template #action="{ row }">
        <TableAction outside :actions="getActions(row)" />
      </template>
    </vxe-grid>

    <div style="
        width: 100%;
        margin-top: 8px;
        margin-bottom: 8px;
        background: white;
        text-align: center;
      ">
      <Button type="primary" @click="submitFn">提起审批</Button>
      <!--      <Button type="warning" @click="openWaitFn" v-if="waitList.length">还有正在等待提交处理的数据</Button>-->
    </div>

    <FormModal @register="register" @success="handleSuccess" />
    <ExcludeDataModal @register="excludeModal[0]" @success="handleSuccess" />
    <ExcludeAddModal @register="excludeAddModal[0]" @success="handleSuccess" />
    <Modal v-model:visible="visible" title="提示信息" @ok="handleOk">
      <p v-for="(item, index) in msgList">第{{ item.index }}行 {{ item.message }}</p>
    </Modal>

    <Modal v-model:visible="showTxtSuccess" title="关闭成功提示" @ok="handleSuccessOk">
      <div>请在MS系统进行补扣款操作</div>
    </Modal>
  </div>
</template>
<script lang="ts" setup>
import { BasicTable, useTable, TableAction } from '@/components/Table';
import { dklMoneyAffirmPageList, refetch, trialLogList } from '@/api/heng/ywManage';
import {
  BasicTableProps,
  VxeBasicTable,
  VxeGridInstance,
  VxeGridListeners,
  VxeTableDefines,
} from '@/components/VxeTable';
import { vxeTableColumns, vxeTableFormSchema, checkboxCountFn } from './role.data';
import { InfoCircleOutlined } from '@ant-design/icons-vue';
import ExcludeDataModal from '../ywMoneyList/ExcludeDataModal.vue';
import ExcludeAddModal from '../ywMoneyList/ExcludeAddModal.vue';
import { reactive, ref, unref, onMounted, onUnmounted } from 'vue';
import { useUserStore } from '@/store/modules/user';
import { useLocaleStore } from '@/store/modules/locale';

import FormModal from '../ywMoneyList/FormModal.vue';
// import FormModal from './FormModal.vue';

import { useMessage } from '@/hooks/web/useMessage';
import { useModal } from '@/components/Modal';
import { Modal, Tooltip, Button } from 'ant-design-vue';

defineOptions({ name: 'MouldList' });
const { createMessage } = useMessage();
const userStore = useUserStore();

const [register, { openModal, closeModal }] = useModal();
const orderModal = useModal();
const loading = ref(false);
const visible = ref(false);
const msgList = ref([]);
const waitList = ref([]);

const showTxtSuccess = ref(false);

const totalObj = ref({});
const excludeModal = useModal();
const excludeAddModal = useModal();
const localeStore = useLocaleStore();

const tableRef = ref<VxeGridInstance>();

const gridOptions = reactive<BasicTableProps>({
  // keepSource: true,
  editConfig: { trigger: 'click', mode: 'cell', showStatus: true },
  border: true,
  showOverflow: true,
  size: 'mini',
  height: 'auto', // 'auto'
  columns: vxeTableColumns,
  filterConfig: {
    remote: true,
  },
  showFooter: true,
  footerData: [{ seq: '合计' }],
  exportConfig: {
    filename() {
      return `抽成明细导出`;
    },
    excludeFields: ['seq', 'num'], //不需要哪些列
    isFooter: false, //不需要表尾
  },
  // checkboxConfig: {
  //   labelField: 'orderNo',
  //   highlight: true,
  //   reserve: true,
  //   showReserveStatus: true
  // },
  toolbarConfig: {
    slots: {
      buttons: 'toolbar_buttons',
    },
    refresh: true,
  },
  formConfig: {
    // enabled: true,
    items: vxeTableFormSchema,
  },
  pagerConfig: {
    // pageSize: 20,
  },
  proxyConfig: {
    props: {
      result: 'data.list',
      list: 'data.list',
      total: 'data.totalResult',
      message: 'message',
    },
    filter: true,
    ajax: {
      query: ({ page, form, filters }) => {
        return findPageList(page, form, filters);
      },
      // queryAll: async ({ form }) => {
      //   return await demoListApi(form);
      // },
    },
  },
});

const gridEvents: VxeGridListeners<any> = {
  checkboxChange({ checked, row }) {
    // console.log(`勾选：`)
    // console.log(row);

    let rows = tableRef.value?.getCheckboxRecords();

    totalObj.value = checkboxCountFn(rows);
  },
  checkboxAll({ checked, $event }) {
    let rows = tableRef.value?.getCheckboxRecords();
    totalObj.value = checkboxCountFn(rows);
  },
};

function findPageList(page, form, filterList?: VxeTableDefines.FilterCheckedParams<any>[]) {
  let json = {};
  if (filterList && filterList.length) {
    filterList.forEach((e) => {
      const value = e.datas[0];
      let field = e.field;
      json[field + 'Like'] = value;
    });
  }
  if (form.dateArr) {
    form.startTime = form.dateArr[0] + ' 00:00:00';
    form.endTime = form.dateArr[1] + ' 23:59:59';
  } else {
    form.startTime = '';
    form.endTime = '';
  }
  // console.log("----json:", json);

  return dklMoneyAffirmPageList({
    page: page.currentPage,
    pageSize: page.pageSize,
    ...form,
    ...json,
  });
}

const findList = (filterList?: VxeTableDefines.FilterCheckedParams<any>[]) => {
  gridOptions.loading = true;
  // 模拟接口
  let queryJson = {};
  if (filterList && filterList.length) {
    filterList.forEach((e) => {
      const value = e.datas[0];
      let field = e.field;
      queryJson[field + 'Like'] = value;
    });
  }

  return new Promise<any[]>((resolve) => {
    let pp = {
      page: { currentPage: 1, pageSize: 20 },
      form: queryJson,
    };

    gridOptions.proxyConfig.ajax.query(pp).then((res) => {
      gridOptions.loading = false;
      let resultObj = {
        result: res.data.list,
        page: {
          total: res.data.totalResult,
        },
      };

      resolve(res);
    });
  });
};

var openNum = 0;

var interval = 0;

onMounted(() => {
  // findList();
  refetch();

});


function startInterval() {
  interval = setInterval(() => {
    if (openNum == 0) {
      trialLogListFn();
    }
  }, 3000);
}


onUnmounted(() => {
  closeInterval();
})
function closeInterval() {
  clearInterval(interval);
}

// const gridEvents: VxeGridListeners = {
//   sortChange({ field, order }) {
//     console.log(field, order);
//   },
//   filterChange({ filterList }) {
//     findList(filterList);
//   },
// };

function getActions(record) {
  let arr = [];
  let userName = userStore.getUserInfo?.userName;
  if ((record.isClose != 1 && userName == record.userName) || userName == record.createUserName) {
    arr.push({
      // icon: 'clarity:note-edit-line',
      label: '编辑',
      onClick: handleEdit.bind(null, record),
    });
    arr.push({
      // icon: 'ant-design:delete-outlined',
      label: '关闭',
      color: 'error',
      popConfirm: {
        title: '是否确认关闭该费用？',
        placement: 'left',
        confirm: handleClose.bind(null, record),
      },
    });
  }
  if (userName == 'manage') {
  }

  return arr;
}

function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
  });
}

function handleClose(record: Recordable) {
  //console.log(record);

  closeMouldApi(record)
    .then((res) => {
      showTxtSuccess.value = true;
    })
    .catch((res) => {
      createMessage.error(res.message);
    })
    .finally(() => {
      tableRef.value.commitProxy('reload');
    });
}

function handleSuccess() {
  openNum = 0;

  tableRef.value.commitProxy('reload');
}

function handleOk() {
  visible.value = false;
}

function handleSuccessOk() {
  showTxtSuccess.value = false;
}

function openUserModal(record: Recordable, type) {
  record.openType = type; // type 1 看符合退款条件的数据 2 看已有的数据
  orderModal[1].openModal(true, record);
}

function submitFn() {
  const selectRecords = tableRef.value.getCheckboxRecords();
  const selectReserveRecords = tableRef.value.getCheckboxReserveRecords();

  let selectList = [...selectRecords, ...selectReserveRecords];

  if (selectList.length == 0) {
    createMessage.error('请选择要审批的数据!');
    return;
  }
  // console.log("----selectList-----");

  // console.log(selectList);
  openModal(true, {
    selectList: unref(selectList),
    type: 2,
  });
  if(!interval){
    startInterval();
  }
}

function addExcludeFn() {
  const selectRecords = tableRef.value.getCheckboxRecords();
  const selectReserveRecords = tableRef.value.getCheckboxReserveRecords();

  let selectList = [...selectRecords, ...selectReserveRecords];

  if (selectList.length == 0) {
    createMessage.error('请选择要排除的数据!');
    return;
  }
  excludeAddModal[1].openModal(true, {
    selectList: unref(selectList),
  });
}

function getExcludeFn() {
  excludeModal[1].openModal(true, { types: '销售订单' })
}

function trialLogListFn() {
  trialLogList({ type: 2 }).then((res) => {
    if (res.code == 200) {
      waitList.value = res.data;
      // console.log("--res.data:", res.data);

      localeStore.setWaitList(res.data);
    }
  });
}
function openWaitFn() {
  let parameter = waitList.value[0].list;
  let selectList = JSON.parse(parameter);
  openNum = 1;
  openModal(true, {
    selectList,
    type: 1,
    wait: true,
  });
}
</script>
<style lang="less">
.isReturn_clazz {
  text-align: center;
  cursor: pointer;
}

.table-header-btn {
  padding-left: 10px;
  color: gray;
  font-size: 12px;
  cursor: pointer;
}
</style>
